import { connect } from 'react-redux'
import { updateUserInfo } from '../actions'
import React from 'react'
import { Col, FieldGroup, ControlLabel, Button, FormControl, FormGroup, Form } from 'react-bootstrap'

class UserCenter extends React.Component {
  constructor(props) {
    super(props)

    this.state = {
      phone: this.props.user.phone,
      location: this.props.user.location,
      mail: this.props.user.mail
    }
  }

  handleLocationChange (e) {
    this.setState({location: e.target.value})
  }

  handlePhoneChange (e) {
    this.setState({phone: e.target.value})
  }

  handleMailChange (e) {
    this.setState({mail: e.target.value})
  }

  handleSubmit (e) {
    e.preventDefault()
    if (!this.state.location || !this.state.phone || !this.state.mail) {
      alert('请填写完毕', this.state)
      return
    }
    this.props.updateUserInfo({location:this.state.location, phone:this.state.phone, mail: this.state.mail})
    alert('更新成功！')
  }

  render () {
   return(
    <Col xs={6} xsOffset={3}>
      <Form onSubmit={(e) => { this.handleSubmit(e) }}>
        <FormGroup controlId="formValidationSuccess1">
          <ControlLabel>邮箱</ControlLabel>
          <FormControl type="text"
            value={this.state.mail} onChange={(e)=>{this.handleMailChange(e)}}/>
        </FormGroup>
        <FormGroup controlId="formValidationSuccess1">
          <ControlLabel>邮寄地址</ControlLabel>
          <FormControl type="text"
            value={this.state.location} onChange={(e)=>{this.handleLocationChange(e)}}/>
        </FormGroup>
        <FormGroup controlId="formValidationSuccess2">
          <ControlLabel>联系电话</ControlLabel>
          <FormControl type="text"
            value={this.state.phone} onChange={(e)=>{this.handlePhoneChange(e)}} />
        </FormGroup>

        <Button type="submit" block>
          提交
        </Button>
      </Form>
    </Col>
    )
  }
}

const mapStateToProps = (state, ownProps) => {
  return {
    user: state.user
  }
}

const mapDispatchToProps = (dispatch, ownProps) => {
  return {
    updateUserInfo: (location, phone) => {
      dispatch(updateUserInfo(location, phone))
    }
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(UserCenter)